﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using KylinORM.CQRS.Publisher;

namespace KylinORM.CQRS.Subscriber.Generic
{
    /// <summary>
    /// 泛型消息响应
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class MessageHandler<T> : MessageHandler where T : IMessage
    {
        public MessageHandler()
        {
        }
        public MessageHandler(params Action<T>[] callbackFunc)
            : base(callbackFunc)
        {
        }
        public MessageHandler(params MessageHandlerItem<T>[] handlerItem)
            : base(handlerItem)
        {
        }

        protected override void ApplyMessage(IMessage message, MessageHandlerItem handlerItem)
        {
            //执行依赖条件
            foreach (MessageHandlerItem item in handlerItem.dependsOn.OrderBy(d => (int)d.MessageLevel))
            {
                this.ApplyMessage(message, item);
            }
            //执行响应的回调方法
            EMessageType messageType = handlerItem.MessageType ?? message.MessageType;
            if (message.MessageType == messageType)
            {
                ((Action<T>)handlerItem.CallbackFunc)((T)message);
            }
            else
            {
                ((Action<T>)handlerItem.CallbackFunc).BeginInvoke((T)message, null, null);
            }
        }

    }
}
